package com.holystone.orca.util.systemInfo;

import com.sun.management.OperatingSystemMXBean;

import java.io.File;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.lang.management.ManagementFactory;
import java.math.BigDecimal;

/**
 *Copyright (c) 2017, HOLYSTONE Technologies, Inc.
 * All right reserved.
 * @desc: windows平台下 操作系统信息
 * @author qijunxing
 * @date 2017年7月17日下午4:43:26
*/
public class WindowsInfo implements SystemInfo {

	
	
	 private static final int CPUTIME = 100; 

	 private static final int PERCENT = 100; 

	 private static final int FAULTLENGTH = 10; 
		
	
	@Override
	public String DiskMessage() {
		//分别计算每个盘符下的  空存储和已使用存储
		long allTotal = 0;
	    long allFree = 0;
	    for (char c = 'A'; c <= 'Z'; c++) {
	    String dirName = c + ":/";
	    File win = new File(dirName);
	    if (win.exists()) {
	    long total = (long) win.getTotalSpace();
	    long free = (long) win.getFreeSpace();
	    allTotal = allTotal + total;
	    allFree = allFree + free;
	      }
	    }
	    Double precent = (Double) (1 - allFree * 1.0 / allTotal) * 100;
	    BigDecimal b1 = new BigDecimal(precent);
	    precent = b1.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
	    return precent+"%";
	}

	@Override
	public String CPUMessage() {
		 try {  
	            String procCmd = System.getenv("windir") + "//system32//wbem//wmic.exe process get Caption,CommandLine,KernelModeTime,ReadOperationCount,ThreadCount,UserModeTime,WriteOperationCount";  
	            // 取进程信息  
	            long[] c0 = readCpu(Runtime.getRuntime().exec(procCmd));  
	            Thread.sleep(CPUTIME);  
	            long[] c1 = readCpu(Runtime.getRuntime().exec(procCmd));  
	            if (c0 != null && c1 != null) {  
	                long idletime = c1[0] - c0[0];  
	                long busytime = c1[1] - c0[1];  
	                return (Double.valueOf(PERCENT * (busytime) / (busytime + idletime)).doubleValue()) +"%";  
	            } else {  
	                return "0.0%";  
	            }  
	        } catch (Exception ex) {  
	            ex.printStackTrace();  
	            return "0.0%";  
	        }  
	}
    
	 /** 
     * 读取CPU信息. 
     * @param proc 
     * @return 
     * @author GuoHuang 
     */  
    private  long[] readCpu(final Process proc) {  
        long[] retn = new long[2];  
        try {  
            proc.getOutputStream().close();  
            InputStreamReader ir = new InputStreamReader(proc.getInputStream());  
            LineNumberReader input = new LineNumberReader(ir);  
            String line = input.readLine(); 
          
            if (line == null || line.length() < FAULTLENGTH) {  
                return null;  
            }  
            int capidx = line.indexOf("Caption");  
            int cmdidx = line.indexOf("CommandLine");  
            int rocidx = line.indexOf("ReadOperationCount");  
            int umtidx = line.indexOf("UserModeTime");  
            int kmtidx = line.indexOf("KernelModeTime");  
            int wocidx = line.indexOf("WriteOperationCount");  
            long idletime = 0;  
            long kneltime = 0;  
            long usertime = 0; 
            while ((line = input.readLine()) != null) {  
                if (line.length() < wocidx) {  
                    continue;  
                }  
                // 字段出现顺序：Caption,CommandLine,KernelModeTime,ReadOperationCount,  
                // ThreadCount,UserModeTime,WriteOperation  
                String caption = Bytes.substring(line, capidx, cmdidx - 1).trim();  
                String cmd = Bytes.substring(line, cmdidx, kmtidx - 1).trim();  
                if (cmd.indexOf("wmic.exe") >= 0) {  
                    continue;  
                }  
                String s1 = Bytes.substring(line, kmtidx, rocidx - 1).trim();  
                String s2 = Bytes.substring(line, umtidx, wocidx - 1).trim();  
                if (caption.equals("System Idle Process") || caption.equals("System")) {  
                    if (s1.length() > 0)  
                        idletime += Long.valueOf(s1).longValue();  
                    if (s2.length() > 0)  
                        idletime += Long.valueOf(s2).longValue();  
                    continue;  
                }  
                if (s1.length() > 0){
                	if(s1.indexOf("")>0||"".equals(s1) ||s1.indexOf("^[A-Za-z]+$")>0){
              		  continue;  
              	    }
                    kneltime += Long.valueOf(s1).longValue();  }
                if (s2.length() > 0) {
                	if(s2.indexOf("")>0||"".equals(s2) ||s2.indexOf("^[A-Za-z]+$")>0){
                		  continue;  
                	}
                   //System.out.println(s2);                
                   usertime += Long.valueOf(s2).longValue();  }
            }  
            retn[0] = idletime;  
            retn[1] = kneltime + usertime;  
            return retn;  
        } catch (Exception ex) {  
            ex.printStackTrace();  
        } finally {  
            try {  
                proc.getInputStream().close();  
            } catch (Exception e) {  
                e.printStackTrace();  
            }  
        }  
        return null;  
    }  
    
	
	  static class Bytes {  
	        /** 
	         * 由于String.subString对汉字处理存在问题（把一个汉字视为一个字节)，因此在 包含汉字的字符串时存在隐患，现调整如下： 
	         *  
	         * @param src 要截取的字符串 
	         * @param start_idx 开始坐标（包括该坐标) 
	         * @param end_idx 截止坐标（包括该坐标） 
	         * @return 
	         */  
	        public static String substring(String src, int start_idx, int end_idx) {  
	            byte[] b = src.getBytes();  
	            String tgt = "";  
	            for (int i = start_idx; i <= end_idx; i++) {  
	                tgt += (char) b[i];  
	            }  
	            return tgt;  
	        }  
	     }
	  
	  
	@Override
	public String MemoryMessage() {
		
		OperatingSystemMXBean osmxb = ManagementFactory.getPlatformMXBean(OperatingSystemMXBean.class);
		long totalvirtualMemory = osmxb.getTotalSwapSpaceSize(); // 剩余的物理内存
		long freePhysicalMemorySize = osmxb.getFreePhysicalMemorySize();
		Double compare = (Double) (1 - freePhysicalMemorySize * 1.0 / totalvirtualMemory) * 100;
		String str = compare.intValue() + "%";
		return str;
	}
    
	public static void main(String[] args) {
		WindowsInfo w=		new WindowsInfo();
		System.out.println(w.DiskMessage());
		System.out.println(w.CPUMessage());
		System.out.println(w.MemoryMessage());
	}
}
